package cn.iocoder.yudao.module.wecom.handler;

import cn.hutool.extra.spring.SpringUtil;
import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils;
import cn.iocoder.yudao.module.wecom.service.customer.WeCustomerService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.constant.WxCpConsts;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 客户联系事件 -- 联系人变更
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@Component
@Slf4j
public class ExternalChangeHandler extends AbstractHandler {


    @Override
    public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map<String, Object> context, WxCpService cpService,
                                    WxSessionManager sessionManager) {

        Map<String, Object> allFieldsMap = wxMessage.getAllFieldsMap();
        WeCustomerService weCustomerService = SpringUtil.getBean(WeCustomerService.class);
        log.info("==================================检测到客户联系人通知事件===============================");
        log.info("==================================检测到客户联系人通知事件：【{}】===============================", wxMessage.getChangeType());
        TenantUtils.executeIgnore(() -> {
            switch (wxMessage.getChangeType()) {
                case WxCpConsts.ExternalContactChangeType.ADD_EXTERNAL_CONTACT: {
                    weCustomerService.addExternalContactHandle(allFieldsMap);
                    break;
                }
                case WxCpConsts.ExternalContactChangeType.DEL_EXTERNAL_CONTACT: {
                    weCustomerService.delExternalExternalContactHandle(allFieldsMap);
                    break;
                }
                case WxCpConsts.ExternalContactChangeType.DEL_FOLLOW_USER: {
                    weCustomerService.delFollowExternalContactHandle(allFieldsMap);
                    break;
                }
            }
        });
        log.info("==================================检测到客户联系人通知事件, 处理结束===============================");

        return null;
    }

}
